<template>
  <a-table :columns="TableColumns" :data="ParentColumns" :pagination="false">
    <template #hide="{ record }">
      <a-button @click="record.hide = !record.hide">
        <template #icon>
          <component :is=" record.hide ? 'IconEyeInvisible' : 'IconEye' " :size="20" />
        </template>
      </a-button>
    </template>
    <template #width="{ record, rowIndex }">
      <a-input-number v-model="record.width" :key="rowIndex" allow-clear style="width: 100px;" />
    </template>
    <template #moveLeft="{ rowIndex }">
      <a-button v-if="rowIndex !== 0" @click="moveLeft(rowIndex)">
        <template #icon>
          <component :is="'IconToTop'" :size="20" />
        </template>
      </a-button>
    </template>
    <template #moveRight="{ rowIndex }">
      <a-button v-if="rowIndex < ParentColumns.length -1" @click="moveRight(rowIndex)">
        <template #icon>
          <component :is="'IconToBottom'" :size="20" />
        </template>
      </a-button>
    </template>
  </a-table>
</template>

<script lang="ts">
import { defineComponent, ref, reactive, watch } from "vue";

export default defineComponent({
  name: "ColumnConfig",
  props: {
    columns: {
      type: Array,
      default: [],
      required: true,
    },
  },
  emits: ["onSyncColumns"],
  setup(props, ctx) {
    const TableColumns = ref([
      {
        title: "列名",
        dataIndex: "label",
      },
      {
        title: "可见性",
        dataIndex: "hide",
        slotName: "hide",
      },
      {
        title: "宽度",
        dataIndex: "width",
        slotName: "width",
      },
      {
        title: "左移",
        dataIndex: "moveLeft",
        slotName: "moveLeft",
      },
      {
        title: "右移",
        dataIndex: "moveRight",
        slotName: "moveRight",
      },
    ]);

    const ParentColumns = ref(props.columns);

    const statusHandler = (record, idx) => {
      record.hide = !record.hide;
    };

    const swapItems = (idx1, idx2) => {
      let arr = ParentColumns.value;
      arr[idx1] = arr.splice(idx2, 1, arr[idx1])[0];
    };

    const moveLeft = (idx) => {
      swapItems(idx, idx - 1);
    };

    const moveRight = (idx) => {
      swapItems(idx, idx + 1);
    };

    watch(
      () => ParentColumns,
      (nv, ov) => {
        ctx.emit("onSyncColumns", nv);
      },
      { deep: true }
    );

    return {
      TableColumns,
      statusHandler,
      ParentColumns,
      moveLeft,
      moveRight,
    };
  },
});
</script>

<style lang="less" scoped>
</style>
